// pages/tags/tags.js
const app = getApp();

Component({

  /**
   * 页面的初始数据
   */
  data: {
    tags: [],
    isDeleting: false, // 是否正在删除中
    tag: {
      id: '',
      label: '',
      icon: '/lib/images/tag.png',
      isNew: true // 表示为新增tag
    }
  },

  observers: {
    'tags.**': function (tags) {
      // 过滤掉没有填写标签名的新tag
      tags = tags.filter(tag => {
        return !tag.isNew;
      });

      // 同步数据到app.globalData.tags中
      app.globalData.tags = tags;
      // 存储到本地storage中
      wx.setStorageSync('tags', JSON.stringify(tags));
    }
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.setData({
        tags: app.globalData.tags
      });
    },

    activeAdd () {
      wx.vibrateShort({
        type: 'heavy'
      });

      this.data.tag.id = app.methods.createRandomStr(10);
      const tags = [...this.data.tags, this.data.tag];
      this.setData({
        tags,
        isDeleting: false
      });
    },

    addTag (e) {
      const tag = e.currentTarget.dataset.tag;
      const index = e.currentTarget.dataset.index;
      const tagName = e.detail.value.trim();
      const key = `tags[${index}]`;

      if (tagName) {
        delete tag.isNew;
        tag.label = tagName;

        this.setData({
          [key]: tag
        });
      }
    },

    activeDelete () {
      wx.vibrateShort({
        type: 'heavy'
      });

      this.setData({
        isDeleting: !this.data.isDeleting
      });
    },

    deleteTag (e) {
      wx.vibrateShort({
        type: 'heavy'
      });

      const tag = e.currentTarget.dataset.tag;

      const tags = this.data.tags.filter(_tag => {
        return tag.id !== _tag.id;
      });
      this.setData({
        tags
      });
    }
  }
})